<?php
/**
 * Created by PhpStorm.
 * User: 胥九庆
 * Date: 2023/01/07
 * Time: 11:47
 */
declare (strict_types=1);

namespace app\common\model;

class ContractLevel extends Base
{
    /**
     * 升级
     */
    public static function upgrade($uid)
    {
        try {
            $list = Relation::alias('a')->leftJoin('user b', 'a.uid = b.id')
                ->where(['a.new_uid' => $uid, 'b.is_del' => 0])
                ->field('b.id, b.contract_level_id, a.algebra')->order('a.algebra', 'asc')->select();
            if ($list) {
                foreach ($list as $val) {
                    $puser = User::find($val->id);self::grade($puser);
                    //if($puser = User::find($user->parent_id)) self::grade($puser);
                }
            }
        } catch (\Exception $e) {

            return $e->getMessage();
        }

        return true;
    }

    private static function grade($user, $level_id=5)
    {
        if(in_array($level_id, [1,2,3,4,5])){
            $level = parent::where('id', $level_id)->order('id asc')->find();
            $count = User::where(['parent_id' => $user->id, 'is_del' => 0])->whereRaw('team_dedicate + my_dedicate >= '.$level->amount)->count('id');

            if($level_id > 0 && $count < $level->count){
                $level_id -- ;
                return self::grade($user, $level_id);
            }

            $before_id = $user->contract_level_id;
            $after_id = $level_id;
            if($before_id != $after_id){
                UserLevelLog::levelLog($user, 11, $before_id, $after_id);
                $user->contract_level_id = $level_id;
                $user->save();
            }
        }

        return true;
    }


    /*public static function upgrade($uid)
    {
        try {
            $list = Relation::alias('a')->leftJoin('user b', 'a.uid = b.id')
                ->where(['a.new_uid' => $uid, 'b.is_del' => 0])
                ->field('b.id, b.contract_level_id, a.algebra')->order('a.algebra', 'asc')->select();
            if ($list) {
                foreach ($list as $val) {
                    $level = parent::where('id', '>', $val->contract_level_id)->order('id asc')->find();
                    $count = User::where(['parent_id' => $val->id, 'is_del' => 0])->where('team_dedicate', '>=', $level->amount)->count('id');
                    if ($count >= $level->count) {
                        User::update(['contract_level_id' => $level->id], ['id' => $val->id]);
                    }
                }
            }
        } catch (\Exception $e) {

            return $e->getMessage();
        }

        return true;
    }*/
}